package com.rcadmin.busi.templateapi.dto;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ArrayUtils;
import org.springframework.util.StringUtils;

import com.google.common.collect.Lists;

/**
 * 指定内容请求
 * 
 * @author tanson lam
 * @create 2016年11月7日
 */
public class SpecBlockReq {
	/**
	 * 分类key
	 */
	private String groupKey;
	/**
	 * 内容ID
	 */
	private Integer[] blockIds;

	public SpecBlockReq(String groupKey, Integer[] blockIds) {
		super();
		this.groupKey = groupKey;
		this.blockIds = blockIds;
	}

	public String getGroupKey() {
		return groupKey;
	}

	public void setGroupKey(String groupKey) {
		this.groupKey = groupKey;
	}

	public Integer[] getBlockIds() {
		return blockIds;
	}

	public void setBlockIds(Integer[] blockIds) {
		this.blockIds = blockIds;
	}

	/**
	 * 判断分类KEY是否在指定内容中
	 * 
	 * @param specBlockReqList
	 * @param groupKey
	 * @return
	 */
	public static Boolean isInSpecBlockReq(List<SpecBlockReq> specBlockReqList,
			String groupKey) {
		if (CollectionUtils.isEmpty(specBlockReqList)
				|| StringUtils.isEmpty(groupKey))
			return false;
		for (SpecBlockReq specBlockReq : specBlockReqList) {
			if (groupKey.equals(specBlockReq.getGroupKey()))
				return true;
		}
		return false;
	}

	/**
	 * 解析请求URL中如果有指定内容信息，则包装到列表中返回
	 * 
	 * @param urlReqParam
	 *            如： 分类key!bId=111&分类key2!bId=333
	 * @return
	 */
	public static List<SpecBlockReq> parse2SpecBlockReq(String urlReqParam) {
		if (StringUtils.isEmpty(urlReqParam))
			return Lists.newArrayList();

		String[] params = urlReqParam.split("&");
		if (ArrayUtils.isEmpty(params))
			return Lists.newArrayList();

		List<SpecBlockReq> list = Lists.newArrayList();
		String bIdSign = "!bId";
		for (String param : params) {
			if (param.contains(bIdSign)) {
				String[] paramKeyValue = StringUtils.split(param, "=");
				String groupKey = StringUtils.replace(paramKeyValue[0],
						bIdSign, "");
				String[] blockIds = paramKeyValue[1].split(",");
				List<Integer> blockList = Lists.newArrayList();
				if (blockIds == null)
					continue;

				for (String blockId : blockIds) {
					blockList.add(Integer.valueOf(blockId));
				}
				
				list.add(new SpecBlockReq(groupKey, blockList
						.toArray(new Integer[blockList.size()])));
			}
		}
		return list;
	}

	public static void main(String[] args) {
		String[] blockIds = "56".split(",");
		System.out.println(blockIds);
	}
}
